package logic

import (
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/core/models"
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileDownloadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileDownloadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileDownloadLogic {
	return &FileDownloadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileDownloadLogic) FileDownload(req *types.FileDownloadRequest, w http.ResponseWriter) (resp *types.FileDownloadResponse, err error) {
	rp := &models.RepositoryPool{}
	err = l.svcCtx.DbConn.Model(&models.RepositoryPool{}).Where("identity=?", req.RepositoryIdentity).First(rp).Error
	if err != nil {
		return
	}
	name := rp.Name
	split := strings.Split(rp.Path, "/")
	var bucketName string
	var objectName string
	for i := 0; i < len(split); i++ {
		if i == 1 {
			bucketName = split[i]
		}
		if i == len(split)-1 {
			objectName = split[i]
		}
	}
	file, err := l.svcCtx.MinioClient.GetObject(context.Background(), bucketName, objectName, minio.GetObjectOptions{})
	defer file.Close()
	if err != nil {
		return
	}
	stat, err := file.Stat()

	data := make([]byte, stat.Size)
	file.Read(data)
	_, err = w.Write(data)
	if err != nil {
		fmt.Println(err)
	}
	w.Header().Set(httpx.ContentType, "application/octet-stream")
	//TODO此处加了之后下载不了，需要研究
	//w.Header().Set("Content-Length", "730981")
	w.Header().Set("Content-Disposition", "attachment;filename="+name)
	return
}
